<script setup lang="ts">
import { ref, onMounted, reactive, watch } from "vue";
import { ElMessage, ElForm, ElFormItem, ElInput, ElCheckboxGroup, ElCheckbox, ElButton, ElMessageBox, ElDivider } from "element-plus";
import { useRoute } from "vue-router";
import { getProductDeptGroupConfigsApi, setProductDeptGroupConfigsApi } from '@/api/configs/productDeptConfig';
import { formatTimestampToDatetime } from "@/utils/appCommon/timeUtil";

const configGroupName = "extraAttribute";

const props = defineProps<{
  searchForm: {
    default: {
      deptId: 0,
      productId: 0,
    };
  };
}>();

// 定义配置项类型
interface ExtraAttributeItem {
  id: string; // 唯一标识，用于删除
  configKey: string; // 属性标识
  displayName: string; // 显示名称
  dependentAttrs: string[]; // 依赖属性
  formula: string; // 计算公式
}

// 物联网参数选项
const paramOptions = ref([])

const route = useRoute();
const formRef = ref<InstanceType<typeof ElForm>>();
const defaultConfig = {
  productId: 0,
  deptId: 0,
  groupName: configGroupName,
  attributes: [],
  updatedAt: ''
}
// 初始化表单数据
const formData = reactive<{
  productId: number;
  deptId: number;
  groupName: string;
  attributes: ExtraAttributeItem[];
  updatedAt: string;
}>(Object.assign({}, defaultConfig));

// 生成唯一ID
const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
};

// 添加新属性区域
const addAttribute = () => {
  formData.attributes.push({
    id: generateId(),
    configKey: '',
    displayName: '',
    dependentAttrs: [],
    formula: ''
  });
};

// 删除属性区域
const removeAttribute = (id: string) => {
  formData.attributes = formData.attributes.filter(item => item.id !== id);
};

// 表单验证规则
const rules = reactive({
  attributes: [
    {
      required: true,
      type: 'array',
      min: 1,
      message: '请至少添加一个额外属性',
      trigger: 'submit'
    }
  ]
});

onMounted(() => {
  if (props.searchForm) {
    formData.productId = props.searchForm.productId;
    formData.deptId = props.searchForm.deptId;
    loadConfigData();
  }
});
watch(() => props.searchForm, (newVal:any) => {
  if (newVal) {
    console.log(newVal);
    formData.attributes = []
    formData.productId = newVal.productId;
    formData.deptId = newVal.deptId;
    loadConfigData();
  }
},{
  deep: true
});

// 初始化表单数据
const loadConfigData = () => {
  if (formData.productId && formData.deptId){
    getProductDeptGroupConfigsApi({
      productId: formData.productId,
      deptId: formData.deptId,
      groupName: formData.groupName
    }).then(res => {
      if (res.code === 0 && res.data?.configs) {
        formData.updatedAt = res.data.updatedAt || '';
        // 解析配置数据到属性数组
        try {
          const configData = JSON.parse(res.data.configs[0]?.configValue || '[]');
          if (Array.isArray(configData)) {
            formData.attributes = configData.map(item => ({
              id: generateId(),
              configKey: item.configKey || '',
              displayName: item.displayName || '',
              dependentAttrs: item.dependentAttrs || [],
              formula: item.formula || ''
            }));
          }
        } catch (e) {
          console.error('解析配置数据失败', e);
          // 如果解析失败，至少添加一个空属性
          addAttribute();
        }
      }
    });
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  try {
    // 1. 先进行表单验证
    await formRef.value.validate();

    // 2. 准备提交数据
    const submitData = {
      productId: formData.productId,
      deptId: formData.deptId,
      groupName: formData.groupName,
      configs: [{
        configKey: 'extraAttributes',
        configValue: JSON.stringify(formData.attributes),
        configDesc: '部门产品额外属性配置'
      }]
    };

    // 3. 验证通过后显示二次确认框
    ElMessageBox.confirm(
      '确定要保存当前额外属性配置吗？',
      '确认提交',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      await setProductDeptGroupConfigsApi(submitData);
      ElMessage.success('保存成功');
    }).catch(() => {
      // 用户取消提交
      ElMessage.info('已取消保存');
    });
  } catch (error) {
    ElMessage.error('表单验证失败，请检查填写内容');
  }
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
  formData.attributes = [];
  addAttribute();
};
</script>

<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="160px" class="form-container">
    <el-form-item label="产品" prop="productId">
      <el-input :value="formData.productId " disabled />
    </el-form-item>
    <el-form-item label="部门" prop="deptId">
      <el-input :value="formData.deptId" disabled />
    </el-form-item>
    <el-form-item label="配置组名" prop="groupName">
      <el-input v-model="formData.groupName" disabled />
    </el-form-item>

    <!-- 动态属性区域 -->
    <el-form-item label="额外属性配置" prop="attributes">
      <div v-for="(item, index) in formData.attributes" :key="item.id" class="attribute-container">
        <div class="attribute-header">
          <h4>属性 {{ index + 1 }}</h4>
          <el-button
            type="danger"
            size="small"
            icon="Delete"
            @click="removeAttribute(item.id)"
            v-if="formData.attributes.length > 1"
          >
            删除
          </el-button>
        </div>

        <el-divider />

        <el-form-item
          :label="'属性标识'"
          :prop="`attributes.${index}.configKey`"
          :rules="[{
            required: true,
            message: '请输入属性标识',
            trigger: 'blur'
          }, {
            pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
            message: '只能包含字母、数字和下划线，且以字母开头',
            trigger: 'blur'
          }]"
        >
          <el-input v-model="item.configKey" placeholder="请输入属性标识（英文、数字、下划线）" />
        </el-form-item>

        <el-form-item
          :label="'显示名称'"
          :prop="`attributes.${index}.displayName`"
          :rules="[{
            required: true,
            message: '请输入显示名称',
            trigger: 'blur'
          }]"
        >
          <el-input v-model="item.displayName" placeholder="请输入属性显示名称" />
        </el-form-item>

        <el-form-item
          :label="'依赖属性'"
          :prop="`attributes.${index}.dependentAttrs`"
          :rules="[{
            required: true,
            message: '请至少选择一个依赖属性',
            trigger: 'change'
          }]"
        >
          <el-checkbox-group v-model="item.dependentAttrs">
            <el-checkbox
              v-for="option in paramOptions"
              :key="option.val"
              :label="option.val"
              style="margin-right: 20px; margin-bottom: 10px;"
            >
              {{ option.label }}
            </el-checkbox>
          </el-checkbox-group>
          <div class="form-hint">提示：选择该属性依赖的物联网参数</div>
        </el-form-item>

        <el-form-item
          :label="'计算公式'"
          :prop="`attributes.${index}.formula`"
          :rules="[{
            required: true,
            message: '请输入计算公式',
            trigger: 'blur'
          }]"
        >
          <el-input v-model="item.formula" placeholder="例如: temperature + humidity / 2" />
          <div class="form-hint">提示：使用选中的属性标识进行公式计算，如temperature、humidity等</div>
        </el-form-item>
      </div>

      <!-- 添加属性按钮 -->
      <el-button
        type="primary"
        icon="Plus"
        @click="addAttribute"
        style="margin-top: 15px;"
      >
        新增额外属性
      </el-button>
    </el-form-item>

    <!-- 更新时间显示 -->
    <el-form-item label="更新时间">
      <el-input :value="formatTimestampToDatetime(formData.updatedAt)" disabled placeholder="暂无更新时间" />
    </el-form-item>

    <el-form-item class="form-actions">
      <el-button type="primary" @click="submitForm">提交</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
.form-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
}

.attribute-container {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.attribute-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 30px;
}

.form-hint {
  color: #606266;
  font-size: 12px;
  margin-top: 5px;
}

::v-deep .el-form-item__content {
  flex: 1;
}

::v-deep .el-checkbox {
  margin-right: 15px;
  margin-bottom: 10px;
}
</style>
